using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
using Microsoft.Health.Samples.PatientConnect.TreyResearch.HealthVaultAdapter;
using System.IO;

namespace Microsoft.Health.Samples.PatientConnect.TreyResearch.TreyResearchScheduler
{
    public class ServiceOutboundCalls
    {
        /// <summary>
        /// This method calls methods from PushHealthVaultItemTypes class.
        /// </summary>
        public static void CallOutboundMethods()
        {
            string condition = String.Empty;
            string patientXmlFile = Path.GetFullPath(SchedulerConfig.PatientXmlFilePath);
            string practicesXmlFile = SchedulerConfig.PracticeXmlFilePath;
            string logFileName = SchedulerConfig.LogFile;
            Practice practice = new Practice(practicesXmlFile);
            List<Practice> practiceList = practice.SelectPracticeRecords(condition);
            DateTime lastRunDateTime = GetLastRunDateTime();

            foreach (Practice practiceItem in practiceList)
            {
                string practiceFolderPath = Path.Combine(patientXmlFile, practiceItem.DataFolder);
                string ccrFolderPath = Path.Combine(patientXmlFile, practiceItem.DataFolder + @"\" + Constants.CcrFolderName);
                string ccdFolderPath = Path.Combine(patientXmlFile, practiceItem.DataFolder + @"\" + Constants.CcdFolderName);
                string labResultFolderPath = Path.Combine(patientXmlFile, practiceItem.DataFolder + @"\" + Constants.LabResultsFolderName);
                List<Patient> patientList = new List<Patient>();
                Guid appId = practiceItem.ChildAppId;
                Patient patient = new Patient(practiceFolderPath + @"\" + Constants.PatientXmlFileName);
                patientList = patient.SelectPatientRecords("RegisteredWithHealthVault=true");
                
                foreach (Patient registeredPatient in patientList)
                {
                    PushHealthVaultItemTypes outbound = new PushHealthVaultItemTypes(appId);

                    UploadCcrDocument(ccrFolderPath, registeredPatient, outbound);

                    UploadCcdDocument(ccdFolderPath, registeredPatient, outbound);

                    UploadLabResultDocument(labResultFolderPath, registeredPatient, outbound);
                }
            }
        }

        /// <summary>
        /// Upload LabResult document
        /// </summary>
        /// <param name="labResultFolderPath">LabResult Folder path</param>
        /// <param name="registeredPatient">Patient</param>
        /// <param name="outbound">outbound</param>
        private static void UploadLabResultDocument(string labResultFolderPath, 
                                                    Patient registeredPatient,
                                                    PushHealthVaultItemTypes outbound)
        {
            DirectoryInfo labResultDirInfor = new DirectoryInfo(labResultFolderPath);
            FileInfo[] labResultFileInfo = labResultDirInfor.GetFiles("*.xml");
            foreach (FileInfo finfo in labResultFileInfo)
            {
                if (finfo.Name.Contains(registeredPatient.PatientId.ToString()))
                {
                    outbound.UploadLabResults(Path.Combine(labResultFolderPath, finfo.Name), registeredPatient.PersonId, registeredPatient.RecordId);
                    File.Move(Path.Combine(labResultFolderPath, finfo.Name), Path.Combine(labResultFolderPath, @"Uploaded\" + finfo.Name));
                }
            }
        }

        /// <summary>
        /// Upload CCD Document
        /// </summary>
        /// <param name="ccdFolderPath">ccdFolderPath</param>
        /// <param name="registeredPatient">Patient</param>
        /// <param name="outbound">Outbound</param>
        private static void UploadCcdDocument(string ccdFolderPath,
                                              Patient registeredPatient,
                                              PushHealthVaultItemTypes outbound)
        {
            DirectoryInfo CCDdirInfo = new DirectoryInfo(ccdFolderPath);
            FileInfo[] ccdFileInfo = CCDdirInfo.GetFiles("*.xml");
            foreach (FileInfo finfo in ccdFileInfo)
            {
                if (finfo.Name.Contains(registeredPatient.PatientId.ToString()))
                {
                    outbound.UploadCcd(Path.Combine(ccdFolderPath, finfo.Name), registeredPatient.PersonId, registeredPatient.RecordId);
                    File.Move(Path.Combine(ccdFolderPath, finfo.Name), Path.Combine(ccdFolderPath, @"Uploaded\" + finfo.Name));
                }

            }
        }

        /// <summary>
        /// Upload CCR Document
        /// </summary>
        /// <param name="ccrFolderPath">ccrFolderPath</param>
        /// <param name="registeredPatient">Patient</param>
        /// <param name="outbound">Outbound</param>
        private static void UploadCcrDocument(string ccrFolderPath,
                                              Patient registeredPatient,
                                              PushHealthVaultItemTypes outbound)
        {
            DirectoryInfo dirInfo = new DirectoryInfo(ccrFolderPath);
            FileInfo[] fileInfo = dirInfo.GetFiles("*.xml");
            foreach (FileInfo finfo in fileInfo)
            {
                if (finfo.Name.Contains(registeredPatient.PatientId.ToString()))
                {
                    outbound.UploadCcr(Path.Combine(ccrFolderPath, finfo.Name), registeredPatient.PersonId, registeredPatient.RecordId);
                    File.Move(Path.Combine(ccrFolderPath, finfo.Name), Path.Combine(ccrFolderPath, @"Uploaded\" + finfo.Name));
                }
            }
        }

        /// <summary>
        /// Returns last run date time of the service.
        /// </summary>
        /// <returns>Returns date time value from file.</returns>
        private static DateTime GetLastRunDateTime()
        {
            DateTime lastRunDateTime = DateTime.MinValue;

            string fileName = SchedulerConfig.LastRunLogFile;
            string fullPath = Path.GetFullPath(fileName);

            if (File.Exists(fullPath))
            {
                using (StreamReader readLog = new StreamReader(fullPath))
                {
                    string dateTimeFromFile = readLog.ReadLine();
                    if (!String.IsNullOrEmpty(dateTimeFromFile))
                    {
                        lastRunDateTime = DateTime.Parse(dateTimeFromFile);
                    }
                }
            }
            return lastRunDateTime;
        }
    }
}
